package com.nfit.shopweb.web.api;

import com.nfit.shopcommon.utils.ThreadLocalUtil;
import com.nfit.shopmodel.dto.system.LoginDto;
import com.nfit.shopmodel.entity.system.SysUser;
import com.nfit.shopmodel.vo.common.Result;
import com.nfit.shopmodel.vo.common.ResultCodeEnum;
import com.nfit.shopmodel.vo.system.LoginVo;
import com.nfit.shopmodel.vo.system.ValidateCodeVo;
import com.nfit.shopweb.service.SysUserService;
import com.nfit.shopweb.service.ValidateCodeService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import static com.nfit.shopmodel.vo.common.AuthConst.THREADLOCAL_API_USER;

/**
 * ClassName:UserController
 * Package:com.nfit.shopweb.web.api
 * Description
 *
 * @Author L
 * @Create 2024/11/16 15:46
 */
@Tag(name = "登录接口",description = "登录、退出、生成验证码图片登功能")
@RestController
@RequestMapping("/api/index")
public class IndexController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private ValidateCodeService validateCodeService;

    /**
     * 登入接口
     * @param loginDto 封装前端数据
     * @return token
     */
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto){
        LoginVo vo = userService.login(loginDto);
        return Result.build(vo, ResultCodeEnum.SUCCESS);
    }

    /**
     * 退出功能,根据token删除redis中的登入信息
     * @param token
     * @return
     */
    @GetMapping("/logout")
    public Result logout(@RequestHeader("token") String token){
        userService.logout(token);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }

    /**
     * 生成图片验证码
     */
    @GetMapping("/validateCode")
    public Result validateCode(){
        ValidateCodeVo validateCode = validateCodeService.getValidateCode();
        return Result.build(validateCode, ResultCodeEnum.SUCCESS);
    }

    /**
     * 从线程获取登入信息
     *
     * @return
     */
    @GetMapping("/userinfo")
    public Result getUserInfo(){
        SysUser sysUser = ThreadLocalUtil.get(THREADLOCAL_API_USER);
        return Result.build(sysUser, ResultCodeEnum.SUCCESS);
    }

}